package service

import (
	"afupanel/constant"
	"errors"
	"fmt"
	"time"
)

type Setting struct {
	Id         int64
	CreateTime time.Time
	UpdateTIme time.Time
	Name       string
	Value      string
	Grouping   string
}

func AddDefaultSettings() {
	fmt.Println("添加默认配置：DEFAULT_PORT")
	if _, err := AddSetting(constant.DEFAULT_PORT, "10086", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
	if _, err := AddSetting(constant.DEFAULT_SESSION_EXPIRE, "7200", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
	// 默认授权IP
	if _, err := AddSetting(constant.DEFAULT_AUTH_IP, "", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
	// 默认授权域名
	if _, err := AddSetting(constant.DEFAULT_AUTH_DOMAIN, "", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
	// 默认授权IP
	if _, err := AddSetting(constant.DEFAULT_SITE_PATH, "/home/www", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
	// 默认授权IP
	if _, err := AddSetting(constant.DEFAULT_SITE_BACKUP_PATH, "/home/backup", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
	// 默认登陆错误限制
	if _, err := AddSetting(constant.DEFAULT_IP_ERROR_LIMIT, "5", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
	// 默认限制IP天数
	if _, err := AddSetting(constant.DEFAULT_BAN_IP_DAY, "3", "SYSTEM"); err != nil {
		fmt.Println(err)
	}
}

func GetValue(name string) (has bool, value string, err error) {
	s := Setting{}
	has, err = Engine.Where("name = ?", name).Get(&s)
	if err != nil {
		return false, "", err
	}
	if !has {
		err = errors.New("未找到该配置")
		return false, "", nil
	}
	value = s.Value
	return
}

func AddSetting(name, value, grouping string) (id int64, err error) {
	has, _, err := GetValue(name)
	if err != nil {
		return 0, err
	}
	if has {
		err = errors.New("已经存在名为：" + name + "的配置了请勿重复添加")
		return
	}
	s := Setting{
		CreateTime: time.Now(),
		UpdateTIme: time.Now(),
		Name:       name,
		Value:      value,
		Grouping:   grouping,
	}
	id, err = Engine.Insert(&s)
	if err != nil {
		return -1, err
	}
	return id, err
}
